<template>
  <div>
    <div class="org-breadcrumb">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item>用户与权限管理</el-breadcrumb-item>
        <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="org-container">
      <div class="org-content">
        <div class="org-header">
          <span>权限管理</span>
          <el-button type="primary" plain @click="addPermission">新增功能权限</el-button>
        </div>
        <div class="permission-operator">
          <div>
            <span class="org-label">创建时间</span>
            <el-date-picker
              class="permission-dateRange"
              size="mini"
              v-model="dateValue"
              type="daterange"
              align="right"
              unlink-panels
              value-format="yyyy-MM-dd"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
          </div>
          <div class="permission-filter">
            <el-input
              size="mini"
              v-model="filterStr"
              placeholder="权限名称"
            >
            </el-input>
          </div>
          <div>
            <el-button size="mini" type="primary" @click="currentPage = 1;onSearch()">搜索</el-button>
          </div>
          <div class="org-label org-right">共{{total}}条数据</div>
        </div>
        <div>
          <el-table
            :data="tableData"
            style="width: 100%">
            <el-table-column
              prop="id"
              label="编号">
            </el-table-column>
            <el-table-column
              prop="permName"
              label="权限名称">
            </el-table-column>
            <el-table-column
              prop="permDescription"
              label="权限说明">
            </el-table-column>
            <el-table-column
              prop="createTime"
              label="创建时间">
            </el-table-column>
            <el-table-column
              prop="updateTime"
              label="最近修改时间">
            </el-table-column>
            <el-table-column
              prop="isAble"
              label="状态">
              <template slot-scope="scope">
                <span>{{ scope.row.isAble === 0 ? '启用': '禁用' }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200">
              <template slot-scope="scope">
                <el-button type="text" @click="toggleEnable(scope.row)">{{getEnableText(scope.row.isAble)}}</el-button>
                <el-button type="text" @click="editPermission(scope.row)">编辑</el-button>
                <el-button type="text" @click="deleteConfirm(scope.row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            style="float: right"
            layout="prev, pager, next"
            :total="total"
            :current-page="currentPage"
            @current-change="pageChange">
          </el-pagination>
        </div>
      </div>
    </div>
    <el-dialog
      title="编辑权限"
      :visible.sync="editPermissionPanelVisible"
      :close-on-click-modal="false"
      width="70%">
      <div class="permission-item">
        <span>权限名称</span>
        <el-input v-model="permissionForm.permName" size="small" maxlength="16"></el-input>
      </div>
      <div class="permission-item">
        <span>权限说明</span>
        <el-input
          v-model="permissionForm.permDescription"
          size="small"
          maxlength="160"
          type="textarea"
          :rows="3"
        ></el-input>
      </div>
      <div class="permission-item">
        <span>权限状态</span>
        <el-radio-group v-model="permissionForm.isAble" >
          <el-radio :label="0">启用</el-radio>
          <el-radio :label="1">禁用</el-radio>
        </el-radio-group>
      </div>
      <div class="permission-config-container">
        <div class="permission-config-table">
          <el-tabs type="border-card">
            <el-tab-pane label="PC端功能权限">
              <el-tree
                ref="tree"
                :data="permissionMenuTree"
                show-checkbox
                node-key="id"
                @check="checkPCTree"
                :default-checked-keys="selectedPCPermission"
                :props="permissionMenuTreeProps">
              </el-tree>
            </el-tab-pane>
            <el-tab-pane label="移动端功能权限">
              <el-tree
                ref="mobileTree"
                :data="permissionMenuTree"
                show-checkbox
                node-key="id"
                @check="checkMobileTree"
                :default-checked-keys="selectedMobilePermission"
                :props="permissionMenuTreeProps">
              </el-tree>
            </el-tab-pane>
          </el-tabs>
        </div>
        <div class="permission-config-list">
          <div>
            已选权限{{ selectedPermission.length }}
          </div>
          <el-table
            :data="selectedPermission"
            height="500">
            <el-table-column
              type="index"
              label="序号">
            </el-table-column>
            <el-table-column
              label="端"
              prop="type"
              width="100">
              <template slot-scope="scope">
                <span>{{ scope.row.type === 1 ? 'PC': '移动' }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="功能权限"
              prop="pathStr"
              width="200">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="text" @click="deletePermissionItem(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div class="user-buttons">
        <el-button type="primary" @click="submitUserPermission">确定</el-button>
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    name: "permission-management",
    data() {
      return ({
        filterStr: '',
        permissionForm: {
          isAble: 0,
          permName: '',
          permDescription: '',
        },
        dateValue: [],
        tableData: [],
        total: 0,
        editPermissionPanelVisible: false,
        currentPage: 1,
        permissionList: [],
        permissionMenuTree: [],
        selectedPCPermission: [],
        selectedMobilePermission: [],
        permissionMenuTreeProps: {
          children: 'children',
          label: 'menuName',
          value: 'id'
        },
      })
    },
    computed: {
      selectedPermission: function() {
        const PCList = _.map(this.selectedPCPermission, id => {
          const pathArray = this.getPathByKey(id, 'id', this.permissionMenuTree)
          return ({
            type: 1,
            pathStr: _.join(_.map(pathArray, item => item.menuName), '>'),
            name: _.get(_.last(pathArray), 'menuName', ''),
            menuId: _.get(_.last(pathArray), 'id', ''),
          })
        })
        const mobileList = _.map(this.selectedMobilePermission, id => {
          const pathArray = this.getPathByKey(id, 'id', this.permissionMenuTree)
          return ({
            type: 2,
            pathStr: _.join(_.map(pathArray, item => item.menuName), '>'),
            name: _.get(_.last(pathArray), 'menuName', ''),
            menuId: _.get(_.last(pathArray), 'id', ''),
          })
        })
        return _.concat(PCList, mobileList)
      }
    },
    mounted() {
      this.getPermissionMenuTree()
      this.onSearch()
    },
    methods: {
      getPermissionMenuTree() {
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        this.$http.post(this.GLOBAL.host, {
          "method":"Permission_MenuTree",
          "query":{}
        }).then(res => {
          loading.close()
          this.permissionMenuTree = res.data.data

        })
      },
      toggleEnable(data) {
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });

        this.$http.post(this.GLOBAL.host, {
            method:"Permission_AbleState",
            data: {
              id: data.id,
              isAble: 1 - data.isAble,
            }
          }
        ).then(res => {
          loading.close()
          if (res.data.code == 200) {
            this.$message({
              message: '修改成功',
              type: 'success'
            });
            this.onSearch()
          } else {
            this.$message({
              message: res.data.data,
              type: 'error'
            });
          }
        })
      },
      getEnableText(enable) {
        if (enable == 0) {
          return '禁用'
        }
        return '启用'
      },
      addPermission() {
        this.editPermissionPanelVisible = true
        this.permissionForm = {}
        this.$refs.tree.setCheckedKeys([]);
        this.$refs.mobileTree.setCheckedKeys([]);
      },
      editPermission(data) {
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        this.editPermissionPanelVisible = true
        this.permissionForm = data
        this.$http.post(this.GLOBAL.host, {
            method:"Permission_FindById",
            query: {
              id: data.id,
            }
          }
        ).then(res => {
          loading.close()
          if (res.data.code == 200) {
            this.selectedPCPermission = _.map(_.filter(res.data.data.typeList, item => item.type === 1), data => data.menuId)
            this.selectedMobilePermission = _.map(_.filter(res.data.data.typeList, item => item.type === 2), data => data.menuId)
            this.$refs.tree.setCheckedKeys(this.selectedPCPermission)
            this.$refs.mobileTree.setCheckedKeys(this.selectedMobilePermission)
          } else {
            this.$message({
              message: res.data.data,
              type: 'error'
            });
          }
        })
      },
      deleteConfirm(id) {
        this.$confirm('确定删除', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }).then(() => {
          this.deletePermission(id)
        }).catch(() => null)
      },
      deletePermission(id) {
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });

        this.$http.post(this.GLOBAL.host, {
            method:"Permission_Delete",
            data: {
              id,
            }
          }
        ).then(res => {
          loading.close()
          if (res.data.code == 200) {
            this.$message({
              message: '删除成功',
              type: 'success'
            });
            this.onSearch()
          } else {
            this.$message({
              message: res.data.data,
              type: 'error'
            });
          }
        })
      },
      submitUserPermission() {
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        if (this.permissionForm.id) {
          this.$http.post(this.GLOBAL.host, {
              method:"Permission_Update",
              data: {
                id:this.permissionForm.id,
                isAble:this.permissionForm.isAble,
                permName:this.permissionForm.permName,
                permDescription:this.permissionForm.permDescription,
                typeList: this.selectedPermission,
              }
            }
          ).then(res => {
            loading.close()
            if (res.data.code == 200) {
              this.selectedPCPermission = []
              this.selectedMobilePermission = []
              this.editPermissionPanelVisible = false
              this.$message({
                message: '修改成功',
                type: 'success'
              });
              this.onSearch()
            } else {
              this.$message({
                message: res.data.data,
                type: 'error'
              });
            }
          })
        } else {
          this.$http.post(this.GLOBAL.host, {
              method:"Permission_Add",
              data: {
                isAble:this.permissionForm.isAble,
                permName:this.permissionForm.permName,
                permDescription:this.permissionForm.permDescription,
                typeList: this.selectedPermission,
              }
            }
          ).then(res => {
            loading.close()
            if (res.data.code == 200) {
              this.selectedPCPermission = []
              this.selectedMobilePermission = []
              this.editPermissionPanelVisible = false
              this.$message({
                message: '修改成功',
                type: 'success'
              });
              this.onSearch()
            } else {
              this.$message({
                message: res.data.data,
                type: 'error'
              });
            }
          })
        }
      },
      cancel() {
        this.selectedPCPermission = []
        this.selectedMobilePermission = []
        this.editPermissionPanelVisible = false
      },
      pageChange(pageNum) {
        this.currentPage = pageNum;
        this.onSearch()
      },
      onSearch(lastQuery) {
        this.lastQuery = lastQuery || {
          pageNo: this.currentPage || 1,
          pageSize: 10,
          startDate: this.dateValue ? this.dateValue[0] : '',
          endDate: this.dateValue ? this.dateValue[1] : '',
          keyword: this.filterStr,
        };
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        this.$http.post(this.GLOBAL.host, {
            method:"Permission_List",
            query: this.lastQuery,
          }
        ).then(res => {
          loading.close()
          this.tableData = res.data.data.list
          this.total = res.data.data.total
        })
      },
      getPathByKey(value, key, arr) {
        let temppath = [];
        try {
          function getNodePath(node){
            temppath.push(node);
            //找到符合条件的节点，通过throw终止掉递归
            if (node[key] === value) {
              throw ("GOT IT!");
            }
            if (node.children && node.children.length > 0) {
              for (var i = 0; i < node.children.length; i++) {
                getNodePath(node.children[i]);
              }

              //当前节点的子节点遍历完依旧没找到，则删除路径中的该节点
              temppath.pop();
            }
            else {

              //找到叶子节点时，删除路径当中的该叶子节点
              temppath.pop();
            }
          }
          for (let i = 0; i < arr.length; i++) {
            getNodePath(arr[i]);
          }
        } catch (e) {
          return temppath;
        }
      },
      checkPCTree() {
        this.selectedPCPermission = this.$refs.tree.getCheckedKeys(true)
      },
      checkMobileTree() {
        this.selectedMobilePermission = this.$refs.mobileTree.getCheckedKeys(true)
      },
      deletePermissionItem(data) {
        if (data.type === 1) {
          this.selectedPCPermission = _.reject(this.selectedPCPermission, id => id === data.menuId)
          this.$refs.tree.setCheckedKeys(this.selectedPCPermission)
        } else {
          this.selectedMobilePermission = _.reject(this.selectedMobilePermission, id => id === data.menuId)
          this.$refs.mobileTree.setCheckedKeys(this.selectedMobilePermission)
        }
      }
    }
  }
</script>

<style lang="less">
  .permission-operator {
    display: flex;
    align-items: center;
    > div {
      margin-right: 15px;
    }
    margin-bottom: 10px;
  }
  .permission-filter {
    width: 200px;
  }
  .permission-item {
    display: flex;
    margin: 10px 0;
    > div {
      width: 400px;
    }
    > span {
      margin-right: 20px;
    }
  }
  .permission-config-container {
    display: flex;
    margin-top: 20px;
  }
  .permission-config-table {
    flex-basis: 400px;
    flex-grow: 1;
    flex-shrink: 1;
    padding-right: 20px;
    > div {
      overflow: hidden;
    }
  }
  .permission-config-list {
    flex: 400px 1 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
  }
  .permission-tip {
    font-size: 14px;
    line-height: 40px;
    margin-top: 2px;
  }
</style>
